﻿import ReactMarkdown from "react-markdown";
import {PrismLight as SyntaxHighlighter} from "react-syntax-highlighter";
import {tomorrow} from "react-syntax-highlighter/dist/cjs/styles/prism";
import remarkGfm from 'remark-gfm';
import {useEffect, useState} from "react";
import BubbleBackground from "@/components/BubbleBackground";
import CopyButton from "@/components/CopyButton";

interface MarkdownProps {
    content: string;
}

function Markdown({content}: MarkdownProps) {
    const [activeId, setActiveId] = useState<string>("");
    const headings = content.match(/^#{2,6} .*/gm);
    const toc = headings?.map((heading, index) => {
        const level = heading.match(/^#+/g)?.[0].length || 1;
        const text = heading.replace(/^#+ /, '');
        const id = `heading-${index}`; // 使用索引生成唯一的 id
        return {level, text, id};
    });
    
    useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach(entry => {
                    console.log(entry)
                });
            },
            {
                rootMargin: '-50% 0px -50% 0px',
                threshold: 0
            }
        );
        
        const headings = document.querySelectorAll('h2, h3');
        headings.forEach(heading => {
            observer.observe(heading);
        });
        
        return () => observer.disconnect();
    }, [content]);
    
    const onAnchorClick = (id: string) => {
        setActiveId(id);
        const element = document.getElementById(id);
        if (element) {
            element.scrollIntoView({behavior: 'smooth', block: 'start'});
        }
    };
    
    return (
        <div className="relative w-full m-auto max-w-7xl md:p-8 md:flex ">
            <BubbleBackground/>
            <div className="md:border-r px-6 border-0">
                <ReactMarkdown
                    remarkPlugins={[remarkGfm]}
                    components={{
                        code({className, children, ...props}) {
                            const match = /language-(\w+)/.exec(className || '');
                            // 生成唯一id
                            const id = `code-${Math.random().toString(36).substr(2, 9)}`;
                            return match ? (
                                <div className="relative">
                                    <CopyButton id={id}/>
                                    <SyntaxHighlighter
                                        language={match[1]}
                                        style={tomorrow}
                                        id={id}
                                        className="px-1.5 py-0.5 rounded-md ::-webkit-scrollbar"
                                    >
                                        {String(children).replace(/\n$/, '')}
                                    </SyntaxHighlighter>
                                </div>
                            ) : (
                                <code
                                    className="shadow text-themeColor px-1.5 py-0.5 bg-smallLightArea mx-1 dark:bg-smallDarkArea rounded-md"
                                    {...props}>
                                    {children}
                                </code>
                            );
                        },
                        pre({children}) {
                            return (
                                <>
                                    {children}
                                </>
                            )
                        },
                        h1({children}) {
                            return (
                                <h1 className="text-3xl font-bold mb-4">
                                    {children}
                                </h1>
                            )
                        },
                        h2({children}) {
                            const index = toc?.findIndex(item => item.text === children) || 0;
                            return (
                                <h2 className="text-2xl font-bold mb-4 border-b pb-2">
                                    <a id={`heading-${index}`} className="anchor target:pt-16">
                                        {children}
                                    </a>
                                </h2>
                            )
                        },
                        h3({children}) {
                            const index = toc?.findIndex(item => item.text === children) || 0;
                            return (
                                <h3 className="text-xl font-bold mb-4">
                                    <a id={`heading-${index}`} className="anchor target:pt-16">
                                        {children}
                                    </a>
                                </h3>
                            )
                        },
                        p({children}) {
                            return (
                                <p className="mb-2">
                                    {children}
                                </p>
                            )
                        },
                        blockquote({children}) {
                            return (
                                <blockquote
                                    className="[&_p]:mb-0 border-l-4 border-themeColor bg-gray dark:bg-neutral-700 pl-4 mb-4 py-1">
                                    {children}
                                </blockquote>
                            )
                        },
                        ul({children}) {
                            return (
                                <ul className="list-disc pl-4 mb-4">
                                    {children}
                                </ul>
                            )
                        }
                    }}
                    className="prose prose-zinc dark:prose-invert prose-code:before:hidden prose-code:after:hidden">
                    {content}
                </ReactMarkdown>
            </div>
            <div
                className="w-96 ml-4 rounded-lg px-8 py-6 hidden md:block sticky top-[6rem] h-[calc(100vh-10rem)]">
                <p className="text-xl font-semibold mb-4">目录</p>
                <ul className="overflow-scroll h-72">
                    {toc?.map(item => {
                        return (
                            <li key={item.id} className={`nav-item level-${item.level}`}
                                style={{
                                    paddingLeft: `${item.level * 15}px`,
                                    transition: 'padding 0.3s ease'
                                }}>
                                <a href={`#${item.id}`}
                                   onClick={() => {
                                       onAnchorClick(item.id)
                                   }}
                                   className={`cursor-pointer ${activeId === item.id ? 'text-themeColor' : ''}`}
                                   style={{
                                       transition: 'all 0.3s ease',
                                       scrollBehavior: 'smooth'
                                   }}
                                >{item.text}</a>
                            </li>
                        )
                    })}
                </ul>
            </div>
        </div>
    )
}

export default Markdown;